const router = require('koa-router')();
const scripts = require('./scripts/systemParams');

router.prefix('/api/system/params', '系统参数信息相关接口');

router.post('/create', async (ctx) => {
  let form = ctx.request.body || {};

  if (!form.category) {
    ctx.body = ctx.getResponse('参数分类未指定！');

    return;
  }

  if (!form.value) {
    ctx.body = ctx.getResponse('参数内容未指定！');

    return;
  }

  form.sortValue = form.sortValue || 0;

  let checkRes = await ctx.sqlite.queryForObject(scripts.checkParamExists, form);

  if (checkRes.data.total == 0) {
    ctx.body = await ctx.sqlite.execute(scripts.create, form);
  } else {
    ctx.body = ctx.getResponse();
  }
}, {
  desc: '添加系统参数',
  body: {
    category: { type: 'string', desc: '参数分类' },
    value: { type: 'string', desc: '参数内容' },
    sortValue: { type: 'integer', desc: '排序值' }
  }
});

router.get('/:category', async (ctx) => {
  let category = ctx.params.category;

  ctx.body = await ctx.sqlite.queryForList(scripts.getByCategory, { category });
}, { desc: '获取系统参数列表', category: '参数类型' });

module.exports = router;